#include "loginui.h"
#include "constants.h"
#include <QApplication>
#include <QSettings>
#include <QCryptographicHash>

// 使用命名空间
using namespace RestaurantSystem;

LoginUI::LoginUI(QWidget *parent)
    : QDialog(parent)
    , m_userManager(nullptr)
    , m_mainLayout(nullptr)
    , m_titleLabel(nullptr)
    , m_subtitleLabel(nullptr)
    , m_roleGroupBox(nullptr)
    , m_customerRadio(nullptr)
    , m_adminRadio(nullptr)
    , m_roleButtonGroup(nullptr)
    , m_loginGroupBox(nullptr)
    , m_formLayout(nullptr)
    , m_usernameLabel(nullptr)
    , m_usernameEdit(nullptr)
    , m_passwordLabel(nullptr)
    , m_passwordEdit(nullptr)


    , m_buttonLayout(nullptr)
    , m_loginButton(nullptr)
    , m_registerButton(nullptr)

    , m_currentRole(UserRole::Customer)
    , m_loggedInUserId("")

{
    // 使用用户管理器单例
    m_userManager = &UserManager::instance();
    if (!m_userManager->initialize()) {
        // 临时禁用登录窗口
        this->setEnabled(false);
        
        QMessageBox msgBox(QMessageBox::Critical, "初始化错误", "用户管理器初始化失败", QMessageBox::Ok, nullptr);
        msgBox.setWindowModality(Qt::ApplicationModal);
        msgBox.exec();
        
        // 恢复登录窗口
        this->setEnabled(true);
    }
    


    // 初始化界面
    initializeUI();
    
    // 应用样式
    applyStyleSheet();
}

LoginUI::~LoginUI()
{
    // Qt会自动清理子对象，无需手动删除
}

LoginUI::UserRole LoginUI::getCurrentRole() const
{
    return m_currentRole;
}

QString LoginUI::getLoggedInUserId() const
{
    return m_loggedInUserId;
}

QString LoginUI::getLoggedInUsername() const
{
    return m_loggedInUsername;
}



void LoginUI::initializeUI()
{
    setWindowTitle("餐厅点餐系统 - 用户登录");
    setFixedSize(400, 480);
    setModal(true);
    
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(20);
    m_mainLayout->setContentsMargins(30, 30, 30, 30);

    // 创建各个区域
    createTitleArea();
    createRoleSelection();
    createLoginForm();
    createButtonArea();

    // 添加弹性空间
    m_mainLayout->addStretch();
}

void LoginUI::createTitleArea()
{
    // 主标题
    m_titleLabel = new QLabel("餐厅点餐系统", this);
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setObjectName("titleLabel");
    
    // 副标题
    m_subtitleLabel = new QLabel("欢迎使用，请选择身份登录", this);
    m_subtitleLabel->setAlignment(Qt::AlignCenter);
    m_subtitleLabel->setObjectName("subtitleLabel");

    m_mainLayout->addWidget(m_titleLabel);
    m_mainLayout->addWidget(m_subtitleLabel);
}

void LoginUI::createRoleSelection()
{
    // 角色选择组框
    m_roleGroupBox = new QGroupBox("选择身份", this);
    m_roleGroupBox->setObjectName("roleGroupBox");
    
    QHBoxLayout *roleLayout = new QHBoxLayout(m_roleGroupBox);
    roleLayout->setSpacing(30);
    
    // 创建单选按钮
    m_customerRadio = new QRadioButton("顾客", this);
    m_adminRadio = new QRadioButton("管理员", this);
    
    m_customerRadio->setObjectName("customerRadio");
    m_adminRadio->setObjectName("adminRadio");
    
    // 创建按钮组
    m_roleButtonGroup = new QButtonGroup(this);
    m_roleButtonGroup->addButton(m_customerRadio, static_cast<int>(UserRole::Customer));
    m_roleButtonGroup->addButton(m_adminRadio, static_cast<int>(UserRole::Admin));
    
    // 默认选择顾客
    m_customerRadio->setChecked(true);
    m_currentRole = UserRole::Customer;
    
    // 连接信号（Qt5 使用 buttonClicked(int)）
    connect(m_roleButtonGroup, QOverload<int>::of(&QButtonGroup::buttonClicked),
            this, [this](int){ handleRoleChanged(); });
    
    roleLayout->addWidget(m_customerRadio);
    roleLayout->addWidget(m_adminRadio);
    roleLayout->addStretch();
    
    m_mainLayout->addWidget(m_roleGroupBox);
}

void LoginUI::createLoginForm()
{
    // 登录表单组框
    m_loginGroupBox = new QGroupBox("登录信息", this);
    m_loginGroupBox->setObjectName("loginGroupBox");
    
    m_formLayout = new QGridLayout(m_loginGroupBox);
    m_formLayout->setSpacing(15);
    m_formLayout->setColumnStretch(1, 1);
    
    // 用户名
    m_usernameLabel = new QLabel("用户名:", this);
    m_usernameEdit = new QLineEdit(this);
    m_usernameEdit->setPlaceholderText("请输入用户名");
    m_usernameEdit->setObjectName("usernameEdit");
    
    // 密码
    m_passwordLabel = new QLabel("密码:", this);
    m_passwordEdit = new QLineEdit(this);
    m_passwordEdit->setEchoMode(QLineEdit::Password);
    m_passwordEdit->setPlaceholderText("请输入密码");
    m_passwordEdit->setObjectName("passwordEdit");
    

    

    
    // 添加到布局
    m_formLayout->addWidget(m_usernameLabel, 0, 0);
    m_formLayout->addWidget(m_usernameEdit, 0, 1);
    m_formLayout->addWidget(m_passwordLabel, 1, 0);
    m_formLayout->addWidget(m_passwordEdit, 1, 1);


    
    // 连接输入变化信号

    
    // 连接回车键
    connect(m_usernameEdit, &QLineEdit::returnPressed, this, &LoginUI::handleLogin);
    connect(m_passwordEdit, &QLineEdit::returnPressed, this, &LoginUI::handleLogin);
    
    m_mainLayout->addWidget(m_loginGroupBox);
}

void LoginUI::createButtonArea()
{
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->setSpacing(20);  // 增加按钮间距到20px
    
    // 创建按钮 - 只保留登录和注册
    m_loginButton = new QPushButton("登录", this);
    m_registerButton = new QPushButton("注册", this);
    
    m_loginButton->setObjectName("loginButton");
    m_registerButton->setObjectName("registerButton");
    
    // 设置按钮属性
    m_loginButton->setMinimumHeight(35);
    m_registerButton->setMinimumHeight(35);
    
    // 设置按钮最小宽度 - 增加到120px
    m_loginButton->setMinimumWidth(120);
    m_registerButton->setMinimumWidth(120);
    
    m_loginButton->setDefault(true);
    
    // 连接信号
    connect(m_loginButton, &QPushButton::clicked, this, &LoginUI::handleLogin);
    connect(m_registerButton, &QPushButton::clicked, this, &LoginUI::handleRegister);
    
    // 添加到布局 - 两按钮居中排列
    m_buttonLayout->addStretch();
    m_buttonLayout->addWidget(m_loginButton);
    m_buttonLayout->addWidget(m_registerButton);
    m_buttonLayout->addStretch();
    
    m_mainLayout->addLayout(m_buttonLayout);
}

void LoginUI::applyStyleSheet()
{
    setStyleSheet(R"(
        QDialog {
            background-color: #f5f5f5;
            font-family: "DejaVu Sans", "SimSun", "Microsoft YaHei";
            font-size: 12px;
        }
        
        #titleLabel {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
            margin: 10px 0;
        }
        
        #subtitleLabel {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 10px;
        }
        
        QGroupBox {
            font-size: 14px;
            font-weight: bold;
            color: #2c3e50;
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            margin-top: 10px;
            padding-top: 10px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
            background-color: #f5f5f5;
        }
        
        QRadioButton {
            font-size: 13px;
            color: #34495e;
            spacing: 8px;
        }
        
        QRadioButton::indicator {
            width: 16px;
            height: 16px;
        }
        
        QRadioButton::indicator:unchecked {
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            background-color: white;
        }
        
        QRadioButton::indicator:checked {
            border: 2px solid #3498db;
            border-radius: 8px;
            background-color: #3498db;
        }
        
        QLabel {
            font-size: 13px;
            color: #2c3e50;
            font-family: "DejaVu Sans", "SimSun", "Microsoft YaHei";
        }
        
        QLineEdit {
            font-size: 13px;
            padding: 8px;
            border: 2px solid #bdc3c7;
            border-radius: 4px;
            background-color: white;
        }
        
        QLineEdit:focus {
            border-color: #3498db;
        }
        
        QCheckBox {
            font-size: 12px;
            color: #34495e;
            spacing: 8px;
        }
        
        QCheckBox::indicator {
            width: 16px;
            height: 16px;
        }
        
        QCheckBox::indicator:unchecked {
            border: 2px solid #bdc3c7;
            border-radius: 3px;
            background-color: white;
        }
        
        QCheckBox::indicator:checked {
            border: 2px solid #27ae60;
            border-radius: 3px;
            background-color: #27ae60;
            image: url(:/icons/check.png);
        }
        
        QPushButton {
            font-size: 13px;
            font-weight: bold;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 20px;
            min-width: 120px;
        }
        
        #loginButton {
            background-color: #3498db;
        }
        
        #loginButton:hover {
            background-color: #2980b9;
        }
        
        #loginButton:pressed {
            background-color: #21618c;
        }
        
        #loginButton:disabled {
            background-color: #bdc3c7;
        }
        
        #registerButton {
            background-color: #27ae60;
        }
        
        #registerButton:hover {
            background-color: #229954;
        }
        
        #registerButton:pressed {
            background-color: #1e8449;
        }
        

        

    )");
}

void LoginUI::handleLogin()
{
    if (!validateInput()) {
        return;
    }

    // 禁用界面防止重复点击
    setUIEnabled(false);

    QString username = m_usernameEdit->text().trimmed();
    QString password = m_passwordEdit->text();

    bool loginSuccess = false;
    QString errorMessage;

    try {
        if (m_currentRole == UserRole::Admin) {
            // 管理员登录
            AuthResult result = m_userManager->loginAdmin(password);
            if (result == AuthResult::SUCCESS) {
                loginSuccess = true;
                m_loggedInUserId = "admin"; // 管理员ID
                m_loggedInUsername = username;
            } else {
                errorMessage = "管理员密码错误";
            }
        } else {
            // 顾客登录
            AuthResult result = m_userManager->loginCustomer(username, password);
            if (result == AuthResult::SUCCESS) {
                loginSuccess = true;
                // 获取用户的实际ID
                m_loggedInUserId = m_userManager->getUserIdByUsername(username);
                m_loggedInUsername = username;
            } else {
                errorMessage = "用户名或密码错误，或用户不存在";
            }
        }

        if (loginSuccess) {


            // 发送登录成功信号
            emit loginSuccessful(m_currentRole, m_loggedInUserId, m_loggedInUsername);
            accept(); // 关闭对话框
        } else {
            showErrorMessage(errorMessage);
        }
    } catch (const std::exception &e) {
        showErrorMessage(QString("登录失败: %1").arg(e.what()));
    }

    // 重新启用界面
    setUIEnabled(true);
}

void LoginUI::handleRegister()
{
    if (m_currentRole == UserRole::Admin) {
        showErrorMessage("管理员账户无法注册，请联系系统管理员");
        return;
    }

    if (!validateInput()) {
        return;
    }

    // 禁用界面防止重复点击
    setUIEnabled(false);

    QString username = m_usernameEdit->text().trimmed();
    QString password = m_passwordEdit->text();

    try {
        AuthResult result = m_userManager->registerCustomer(username, password);
        
        if (result == AuthResult::SUCCESS) {
            // 使用非阻塞的方式显示成功消息
            QTimer::singleShot(0, this, [this, username]() {
                // 临时禁用登录窗口
                this->setEnabled(false);
                
                QMessageBox* msgBox = new QMessageBox(QMessageBox::Information, 
                    "注册成功", 
                    QString("用户 '%1' 注册成功！\n现在可以使用新账户登录。").arg(username),
                    QMessageBox::Ok, nullptr);
                msgBox->setAttribute(Qt::WA_DeleteOnClose);
                msgBox->setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
                msgBox->setWindowModality(Qt::ApplicationModal);
                
                // 当对话框关闭时恢复登录窗口
                connect(msgBox, &QMessageBox::finished, this, [this]() {
                    this->setEnabled(true);
                });
                
                msgBox->show();
            });
            
            // 清除密码字段，保留用户名
            m_passwordEdit->clear();
            m_passwordEdit->setFocus();
        } else {
            QString errorMsg = "注册失败：";
            switch (result) {
                case AuthResult::USER_ALREADY_EXISTS:
                    errorMsg += "用户名已存在";
                    break;
                case AuthResult::WEAK_PASSWORD:
                    errorMsg += "密码强度不足\n要求：至少6个字符，包含小写字母和数字";
                    break;
                case AuthResult::INVALID_USERNAME:
                    errorMsg += "用户名格式无效\n要求：3-20个字符，只能包含字母、数字和下划线";
                    break;
                default:
                    errorMsg += "输入无效或系统错误";
                    break;
            }
            showErrorMessage(errorMsg);
        }
    } catch (const std::exception &e) {
        showErrorMessage(QString("注册失败: %1").arg(e.what()));
    }

    // 重新启用界面
    setUIEnabled(true);
}



void LoginUI::handleRoleChanged()
{
    int roleId = m_roleButtonGroup->checkedId();
    m_currentRole = static_cast<UserRole>(roleId);
    
    // 清除输入
    clearInputs();
    
    // 根据角色调整界面
    if (m_currentRole == UserRole::Admin) {
        m_usernameEdit->setPlaceholderText("请输入管理员用户名");
        m_registerButton->setEnabled(false);

    } else {
        m_usernameEdit->setPlaceholderText("请输入用户名");
        m_registerButton->setEnabled(true);

    }
    

}



bool LoginUI::validateInput()
{
    QString username = m_usernameEdit->text().trimmed();
    QString password = m_passwordEdit->text();

    if (username.isEmpty()) {
        showErrorMessage("请输入用户名");
        m_usernameEdit->setFocus();
        return false;
    }

    if (password.isEmpty()) {
        showErrorMessage("请输入密码");
        m_passwordEdit->setFocus();
        return false;
    }

    // 用户名长度检查
    if (username.length() < 3 || username.length() > 20) {
        showErrorMessage("用户名长度应在3-20个字符之间");
        m_usernameEdit->setFocus();
        return false;
    }

    // 密码长度检查
    if (password.length() < 6) {
        showErrorMessage("密码长度不能少于6个字符");
        m_passwordEdit->setFocus();
        return false;
    }

    return true;
}

void LoginUI::showErrorMessage(const QString &message)
{
    if (!message.isEmpty()) {
        // 临时禁用登录窗口
        this->setEnabled(false);
        
        QMessageBox msgBox(QMessageBox::Warning, "错误", message, QMessageBox::Ok, nullptr);
        msgBox.setWindowModality(Qt::ApplicationModal);
        msgBox.exec();
        
        // 恢复登录窗口
        this->setEnabled(true);
    }
}

void LoginUI::clearInputs()
{
    if (m_usernameEdit) {
        m_usernameEdit->clear();
    }
    if (m_passwordEdit) {
        m_passwordEdit->clear();
    }

}

void LoginUI::setUIEnabled(bool enabled)
{
    if (m_usernameEdit) m_usernameEdit->setEnabled(enabled);
    if (m_passwordEdit) m_passwordEdit->setEnabled(enabled);
    if (m_loginButton) m_loginButton->setEnabled(enabled);
    if (m_registerButton) m_registerButton->setEnabled(enabled);
    if (m_customerRadio) m_customerRadio->setEnabled(enabled);
    if (m_adminRadio) m_adminRadio->setEnabled(enabled);
}




